package team.seekers.hula.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import team.seekers.hula.common.entity.result.ApiException;
import team.seekers.hula.common.entity.result.ApiExceptionEnum;
import team.seekers.hula.common.entity.result.ResponseResult;

/**
 * @author Godc
 * @description
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //这个注解表名此方法应该处理什么异常
    @ExceptionHandler(Exception.class)
    @ResponseBody//统一返回类型
    public ResponseResult error(Exception e) {
        e.printStackTrace();
        return ResponseResult.fail(ApiExceptionEnum.UNKNOWN_ERROR);
    }

    //自定义类异常的处理
    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public ResponseResult error(ApiException e) {
        if (e.isPrint()) {
            e.printStackTrace();
        }
        //返回错误码，统一返回类型方便调用
        return ResponseResult.fail().code(e.getCode()).message(e.getMessage());
    }


    // 手动捕获这个异常
    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseResult httpMessageNotReadable(HttpMessageNotReadableException ex){
        ex.printStackTrace();
        return ResponseResult.fail(ApiExceptionEnum.PARAM_NOT_VALID);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        String s =  e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseResult.fail(ApiExceptionEnum.PARAM_NOT_VALID).message(s);
    }


}
